package com.cs2.volunteerpostbackend.web.controller;

import com.cs2.volunteerpostbackend.dao.CommentMapper;
import com.cs2.volunteerpostbackend.dao.MomentMapper;
import com.cs2.volunteerpostbackend.dao.UserMapper;
import com.cs2.volunteerpostbackend.web.dto.RespEntity;
import com.cs2.volunteerpostbackend.web.dto.SqlQueryResult;
import com.cs2.volunteerpostbackend.web.dto.SqlUpdateResult;
import com.cs2.volunteerpostbackend.web.dto.ai.AiRequestDTO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UnifiedAIController {

    private final Map<String, ChatClient> chatClientMap = new HashMap<>();
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private MomentMapper momentMapper;
    
    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    public UnifiedAIController(
            @Qualifier("chatClient") ChatClient chatClient,
            @Qualifier("searchSqlGenerationChatClient") ChatClient searchSqlGenerationChatClient,
            @Qualifier("sqlArgsGenerationChatClient") ChatClient sqlArgsGenerationChatClient
    ) {
        chatClientMap.put("chat", chatClient);
        chatClientMap.put("sqlSearch", searchSqlGenerationChatClient);
        chatClientMap.put("sqlUpdate", sqlArgsGenerationChatClient);
    }

    // 被修改
    @PostMapping("/ai/unified")
    public RespEntity unifiedChat(@RequestBody AiRequestDTO aiRequestDTO) {

        String topic = aiRequestDTO.getTopic();
        String question = aiRequestDTO.getQuestion();
        String userId = aiRequestDTO.getUserId();;

        System.out.println(">>> 接收到统一AI请求: topic=" + topic + ", question=" + question + ", userId=" + userId);

        try {
            if (question == null || question.trim().isEmpty()) {
                System.err.println("!!! 问题参数为空");
                return RespEntity.error("问题不能为空");
            }

            // 如果没有提供topic参数，默认使用chat
            if (topic == null || topic.trim().isEmpty()) {
                topic = "chat";
            }

            // 特殊处理sql topic
            switch (topic) {
                case "sqlSearch" -> {
                    return handleSqlSearchTopic(question, userId);
                }
                case "sqlUpdate" -> {
                    return handleSqlUpdateTopic(question);
                }
                // 特殊处理文生图 topic
                case "image" -> {
                    return handleImageTopic(question);
                }
            }

            ChatClient chatClient = chatClientMap.get(topic);
            if (chatClient == null) {
                System.err.println("!!! 不支持的topic: " + topic);
                return RespEntity.error("不支持的topic: " + topic + "。支持的topic包括: " + chatClientMap.keySet());
            }

            System.out.println(">>> 调用AI模型处理问题");
            String answer = chatClient.prompt()
                    .user(question)
                    .call()
                    .content();

            System.out.println("<<< 成功获取AI回答，长度: " + (answer != null ? answer.length() : 0));
//            System.out.println("<<< AI原始回复内容: " + answer);
            
            // 直接将AI回复转换为JSON格式返回给前端
            Map<String, Object> responseData = parseAiResponse(answer);
            return RespEntity.success(responseData);
        } catch (Exception e) {
            System.err.println("!!! 处理请求时发生错误: " + e.getMessage());
            System.err.println(">>> 错误类型: " + e.getClass().getName());
            e.printStackTrace();

            // 根据错误类型提供更具体的错误信息
            if (e.getMessage() != null && e.getMessage().contains("HTTP 404")) {
                return RespEntity.error("API端点配置错误，请检查base-url配置是否正确");
            } else if (e.getMessage() != null && e.getMessage().contains("401")) {
                return RespEntity.error("API认证失败，请检查API密钥是否正确配置");
            } else if (e.getMessage() != null && e.getMessage().contains("HTTP")) {
                return RespEntity.error("API调用失败: " + e.getMessage());
            }

            return RespEntity.error("抱歉，处理您的请求时出现错误: " + e.getMessage());
        }
    }
    
    // 将AI回复解析为JSON格式
    private Map<String, Object> parseAiResponse(String response) {
        Map<String, Object> result = new LinkedHashMap<>(); // 使用LinkedHashMap保持插入顺序
        
        if (response == null || response.isEmpty()) {
            result.put("chat", "");
            result.put("post_title", "");
            result.put("post_content", "");
            return result;
        }
        
        // 提取chat内容
        String chatContent = extractChatContent(response);
        result.put("chat", chatContent != null ? chatContent.trim() : "");
        
        // 提取帖子标题
        String postTitle = extractPostTitle(response);
        result.put("post_title", postTitle != null ? postTitle.trim() : "");
        
        // 提取帖子内容
        String postContent = extractPostContent(response);
        result.put("post_content", postContent != null ? postContent.trim() : "");
        
        return result;
    }
    
    // 从AI回复中提取chat内容
    private String extractChatContent(String response) {
        if (response == null || !response.contains("chat:")) {
            return response; // 如果没有chat:标签，返回整个响应作为chat内容
        }
        
        // 提取chat:后面的内容
        int chatIndex = response.indexOf("chat:") + 5;
        String chatContent = response.substring(chatIndex).trim();
        
        // 如果找到了post_title:，则截取到那里为止
        int nextTitleIndex = chatContent.indexOf("post_title:");
        if (nextTitleIndex != -1) {
            chatContent = chatContent.substring(0, nextTitleIndex).trim();
        }
        
        return chatContent;
    }
    
    // 从AI回复中提取帖子标题
    private String extractPostTitle(String response) {
        if (response == null || !response.contains("post_title:")) {
            return null;
        }
        
        // 提取post_title:后面的内容
        int titleIndex = response.indexOf("post_title:") + 11;
        String titleContent = response.substring(titleIndex).trim();
        
        // 如果找到了post_content:，则截取到那里为止
        int nextContentIndex = titleContent.indexOf("post_content:");
        if (nextContentIndex != -1) {
            titleContent = titleContent.substring(0, nextContentIndex).trim();
        }
        
        return titleContent;
    }
    
    // 从AI回复中提取帖子内容
    private String extractPostContent(String response) {
        if (response == null || !response.contains("post_content:")) {
            return null;
        }
        
        // 提取post_content:后面的内容
        int contentIndex = response.indexOf("post_content:") + 13;
        String content = response.substring(contentIndex).trim();
        
        return content;
    }
    
    // 处理文生图请求
    private RespEntity handleImageTopic(String question) {
        try {
            // 创建RestTemplate实例
            RestTemplate restTemplate = new RestTemplate();
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-DashScope-Async","enable");
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + System.getenv("DASHSCOPE_API_KEY"));
            
            // 构建请求体
            String requestBody = """
                    {
                          "model": "wan2.2-t2i-flash",
                          "input": {
                              "prompt": "@p"
                          },
                          "parameters": {
                              "size": "1024*1024",
                              "n": 1
                          }
                    }
                    """;
            requestBody = requestBody.replace("@p", question);

            // 创建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

            // 发送POST请求并返回结果
            ResponseEntity<String> response = restTemplate.postForEntity(
                    "https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis",
                    requestEntity,
                    String.class
            );
            
            // 解析响应以提取所需信息
            // 注意：实际应用中应该使用JSON解析库（如Jackson或Gson）来解析响应
            String responseBody = response.getBody();
            
            // 封装响应数据，只返回必要信息
            Map<String, Object> imageData = new HashMap<>();
            imageData.put("taskId", extractTaskIdFromResponse(responseBody));
            imageData.put("message", "图片生成任务已提交");
            imageData.put("status", "processing");
            
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("imageData", imageData);
            
            return RespEntity.success(resultData);
        } catch (Exception e) {
            System.err.println("!!! 处理文生图请求时发生错误: " + e.getMessage());
            e.printStackTrace();
            return RespEntity.error("生成图片时发生错误: " + e.getMessage());
        }
    }

    @RequestMapping(value = "/ai/imageStatus")
    public RespEntity isFinish(String taskId){
        try {
            // 创建RestTemplate实例
            RestTemplate restTemplate = new RestTemplate();
            // 创建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + System.getenv("DASHSCOPE_API_KEY"));
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);
            // 发送GET请求并返回结果
            String url="https://dashscope.aliyuncs.com/api/v1/tasks/"+taskId;
            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    requestEntity,
                    String.class
            );
            
            // 解析响应内容
            String responseBody = response.getBody();
            
            // 提取状态信息
            Map<String, Object> statusData = new HashMap<>();
            statusData.put("taskId", taskId);
            statusData.put("status", extractStatusFromResponse(responseBody));
            statusData.put("imageUrl", extractImageUrlFromResponse(responseBody));

            return RespEntity.success(statusData);
        } catch (Exception e) {
            System.err.println("!!! 查询图片生成状态时发生错误: " + e.getMessage());
            e.printStackTrace();
            return RespEntity.error("查询图片生成状态时发生错误: " + e.getMessage());
        }
    }
    
    // 从响应中提取任务ID
    private String extractTaskIdFromResponse(String response) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response);
            JsonNode taskIdNode = rootNode.path("output").path("task_id");
            return taskIdNode.asText("");
        } catch (Exception e) {
            System.err.println("解析任务ID时出错: " + e.getMessage());
            return "";
        }
    }
    
    // 从响应中提取状态
    private String extractStatusFromResponse(String response) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response);
            JsonNode statusNode = rootNode.path("output").path("task_status");
            return statusNode.asText("UNKNOWN");
        } catch (Exception e) {
            System.err.println("解析状态时出错: " + e.getMessage());
            return "UNKNOWN";
        }
    }
    
    // 从响应中提取图片URL
    private String extractImageUrlFromResponse(String response) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response);
            JsonNode resultsNode = rootNode.path("output").path("results");
            if (resultsNode.isArray() && resultsNode.size() > 0) {
                JsonNode firstResultNode = resultsNode.get(0);
                JsonNode urlNode = firstResultNode.path("url");
                return urlNode.asText("");
            }
            return "";
        } catch (Exception e) {
            System.err.println("解析图片URL时出错: " + e.getMessage());
            return "";
        }
    }
    
    // 处理SQL相关的topic
    private RespEntity handleSqlSearchTopic(String question, String userId) {
        try {
            // 获取AI生成的回复（包含chat消息和SQL语句）
            ChatClient sqlChatClient = chatClientMap.get("sqlSearch");
            String aiResponse = sqlChatClient.prompt()
                    .user(question)
                    .call()
                    .content();
            
            System.out.println(">>> AI生成的原始回复: " + aiResponse);
            
            // 提取chat内容和SQL语句
            String chatContent = extractChatFromResponse(aiResponse);
            String sql = extractSqlFromResponse(aiResponse);
            
            if (sql == null || sql.trim().isEmpty()) {
                return RespEntity.error("无法从AI回复中提取有效的SQL语句");
            }
            
            System.out.println(">>> 提取的SQL语句: " + sql);
            
            // 处理SQL中的userId参数
            Map<String, Object> paramMap = new HashMap<>();
            if (userId != null && !userId.isEmpty()) {
                // 如果提供了userId，添加到参数映射中
                paramMap.put("userId", userId);
                System.out.println(">>> 使用参数化查询，userId: " + userId);
                List<Map<String, Object>> queryResult = namedParameterJdbcTemplate.queryForList(sql, paramMap);
                // 构造结果回复，只包含chat内容和查询结果
                SqlQueryResult result = new SqlQueryResult();
                result.setChat(chatContent);
                result.setQueryData(queryResult);
                return RespEntity.success(result);
            } else {
                // 如果没有提供userId，需要移除相关的条件
                String modifiedSql = sql.replace(" OR m.poster_id = :userId", "");
                System.out.println(">>> 移除userId条件后的SQL语句: " + modifiedSql);
                List<Map<String, Object>> queryResult = namedParameterJdbcTemplate.queryForList(modifiedSql, paramMap);
                // 构造结果回复，只包含chat内容和查询结果
                SqlQueryResult result = new SqlQueryResult();
                result.setChat(chatContent);
                result.setQueryData(queryResult);
                return RespEntity.success(result);
            }
        } catch (Exception e) {
            System.err.println("!!! 处理SQL请求时发生错误: " + e.getMessage());
            e.printStackTrace();
            return RespEntity.error("执行SQL查询时发生错误: " + e.getMessage());
        }
    }

    private RespEntity handleSqlUpdateTopic(String question) {
        try {
            // 获取AI生成的回复（包含chat消息和SQL语句）
            ChatClient sqlChatClient = chatClientMap.get("sqlUpdate");
            String aiResponse = sqlChatClient.prompt()
                    .user(question)
                    .call()
                    .content();

            System.out.println(">>> AI生成的原始回复: " + aiResponse);

            // 提取chat内容和SQL语句
            String chatContent = extractChatFromResponse(aiResponse);
            String sql = extractSqlFromResponse(aiResponse);

            if (sql == null || sql.trim().isEmpty()) {
                return RespEntity.error("无法从AI回复中提取有效的SQL语句");
            }

            System.out.println(">>> 提取的SQL语句: " + sql);

            // 处理SQL中的userId参数
            Map<String, Object> paramMap = new HashMap<>();

            // 如果没有提供userId，需要移除相关的条件
            String modifiedSql = sql.replace(" OR m.poster_id = :userId", "");
            // 构造结果回复，只包含chat内容和查询结果
            SqlUpdateResult result = new SqlUpdateResult();
            result.setChat(chatContent);
            result.setSql(sql);
            return RespEntity.success(result);
        } catch (Exception e) {
            System.err.println("!!! 处理SQL请求时发生错误: " + e.getMessage());
            e.printStackTrace();
            return RespEntity.error("执行SQL查询时发生错误: " + e.getMessage());
        }
    }

    // 从AI回复中提取chat内容
    private String extractChatFromResponse(String response) {
        if (response == null || !response.contains("chat:")) {
            return null;
        }
        
        // 提取chat:后面的内容
        int chatIndex = response.indexOf("chat:") + 5;
        String chatContent = response.substring(chatIndex).trim();
        
        // 如果找到了下一个sql:，则截取到那里为止
        int nextSqlIndex = chatContent.indexOf("sql:");
        if (nextSqlIndex != -1) {
            chatContent = chatContent.substring(0, nextSqlIndex).trim();
        }
        
        return chatContent;
    }
    
    // 从AI回复中提取SQL语句
    private String extractSqlFromResponse(String response) {
        if (response == null || !response.contains("sql:")) {
            return null;
        }
        
        // 提取sql:后面的内容
        int sqlIndex = response.indexOf("sql:") + 4;
        String sql = response.substring(sqlIndex).trim();
        
        // 如果找到了下一个chat:，则截取到那里为止
        int nextChatIndex = sql.indexOf("chat:");
        if (nextChatIndex != -1) {
            sql = sql.substring(0, nextChatIndex).trim();
        }
        
        return sql;
    }
}